﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abp.Configuration;
using Abp.Domain.Repositories;
using KelonProud.Administration.Domain.Application;
using KelonProud.Linq;

namespace KelonProud.Administration.Managers.Application
{
   public  class KelonSettingManager : KelonProudDomainService<Setting,long>
    {
        private readonly IRepository<Setting, long> _manageRepository;

        public KelonSettingManager(IRepository<Setting, long> manageRepository) : base(manageRepository)
        {
            _manageRepository = manageRepository;
        }

        public void SaveSetting(Setting setting)
        {
            var userSettting = GetSetting(setting.Name, setting.UserId.ToInt32());

            if (userSettting != null)
            {
                userSettting.Name = setting.Name;
                userSettting.Value = setting.Value;
                ManagerRepository.Update(userSettting);
            }
            else
            {
                ManagerRepository.Insert(setting);
            }
        }

        public void SaveSetting(string name, string value)
        {
            SaveSetting(new Setting()
            {
                Name = name,
                Value = value,
                UserId = AbpSession.UserId.ToInt32()
            });
        }


        public void DeleteSetting(int id)
        {
            var setting = GetSetting(id);
            if (setting != null)
                ManagerRepository.Delete(setting);
        }

        public Setting GetSetting(int id)
        {
            return Query.FirstOrDefault(f => f.Id == id);
        }

        public Setting GetSetting(string key, int userId)
        {
            return Query.FirstOrDefault(f => f.Name == key && f.UserId == userId);
        }

        public Setting GetSetting(string key)
        {
            return GetSetting(key, AbpSession.UserId.ToInt32());
        }
    }
}
